// pages/product/productlist/productlist.js productKind
let { AJAX, productKind, imgUrl} = require('../../../utils/util.js')
const App = getApp()

Page({
  /**
   * 页面的初始数据 
   */
  data: { 
    navH: '',
     imgUrl: imgUrl,
    typeList: [],
    activeNum:'',
     productList: [],
    page:1,
    total:0,  
    hot: '',
    level:1,
     floorstatus: false,
    
     tabPosition: false,
     search:'',       
     sta:'',
     tabTxt: ['天数', '年龄', '更·多'],//分类
     tab: [true, true, true],
     days: {
        "value": {
           "1": "1天",
           "2": "2天",
           "3": "3天",
           "4": "4天", 
           "5": "5天",
           "6": "6天",
           "7": "7天",
           "8": "8+"
        }
     },
     days_key: '',//天数
     days_txt: '',
     age_key: '',//年龄
     age_txt: '',
   
     result:{},
     address_key:'',
     label_key:'',
     category:[],






    isRefreshing: false,
    isLoadingMoreData: false,
    hasNoData: false, 
  },  
   // 选项卡
   filterTab: function (e) {
      var data = [true, true, true], index = e.currentTarget.dataset.index;
      data[index] = !this.data.tab[index];
      this.setData({
         tab: data,
        isRefreshing:false
      })
   },

   //筛选项点击操作
   filter: function (e) {
      var self = this, id = e.currentTarget.dataset.id, txt = e.currentTarget.dataset.txt, tabTxt = this.data.tabTxt, idx = e.currentTarget.dataset.idx;
      switch (e.currentTarget.dataset.index) {
         case '0':
         
            tabTxt[0] = txt;
            if (this.data.days_key != id) {
               self.setData({
                  tab: [true, true, true],
                  tabTxt: tabTxt,
                  days_key: id,
                  days_txt: txt,
                  page: 1
               });
               console.log(this.data.days_key)
            } else {
               this.setData({
                  tab: [true, true, true],
                  days_key: '',
                  ['tabTxt[0]']: '天数',
                  page: 1
               })
               // self.requestList();
            } 
          
            break;
         case '1':           
            tabTxt[1] = txt;
            if (this.data.age_key!=id){
             self.setData({
                tab: [true, true, true],
                tabTxt: tabTxt,
                age_key: id,
                age_txt: txt,
                page: 1
             });
          } else{
               this.setData({
                 tab: [true, true, true],
                 age_key:'',
                  ['tabTxt[1]']: '年龄',
                  page: 1
              })
              // self.requestList();
          }           
            break;
         case '2':
          //  tabTxt[2] = txt;
            self.setData({
               tab: [true, true, true],
               page: 1
               // tabTxt: tabTxt,
               // xiaoliang_id: id,
               // xiaoliang_txt: txt
            });
            break;
      }
      //数据筛选
      self.requestList();
   },
   // 标签 label_key
   label(e){
      if (this.data.label_key != e.currentTarget.dataset.id) {
         this.setData({
            label_key: e.currentTarget.dataset.id
         })

      } else {
         this.setData({
            label_key: ""
         })
      }
   },
   // 地址address
   address(e){
    
      if (this.data.address_key != e.currentTarget.dataset.id){
           this.setData({
              address_key : e.currentTarget.dataset.id
           }) 
       
      } else{
         this.setData({
            address_key:""
         }) 
      }
   },
   // 分类
   category(e){
       let id=e.currentTarget.dataset.id
      if (this.data.activeNum != id){
         this.setData({
            activeNum:id
         }) 
      } else {
         this.setData({
            activeNum: ""
         })
      }
     
   },
   // reset 重置
   reset(){
      this.setData({
         activeNum: "",
         address_key: "",
         label_key: "",
         ['tabTxt[2]']: '更多',
      })
     

   },
   // 保存
   preserve(e){     
      this.setData({
         tab: [true, true, true],
         page: 1       
      });
      if (this.data.activeNum !== '' || this.data.address_key !== '' || this.data.label_key!==''){
         this.setData({           
            ['tabTxt[2]']: '更·多'
         })
     }
      this.requestList();
   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      navH: App.globalData.navHeight,
      activeNum:options.id || '',
      // hot:options.type||"",
      // ['category[0]']: options.id
    })
   

     if (!wx.getStorageSync("ACCESSTOKEN")) {
        App.userInfoReadyCallback = res => {
           wx.setStorageSync('ACCESSTOKEN', res);
           //this.requestType()
           this.requestList()
           this.getUserInfo()
           this.getSearch()
        }
        return
     }
    //this.requestType()
    this.requestList()
     this.getUserInfo()
     this.getSearch()
  }, 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
   //product/product-search
   getSearch(){
      AJAX('product/product-search', 'GET').then(res => {
          console.log(res)  
         this.setData({
            result:res.data,         
         })
      })
   },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

     this.setData({
        page: 1
     })
     this.requestList()
     // 显示顶部刷新图标
     wx.showNavigationBarLoading();
  },
   bindValue(e){
     // console.log(e.detail.value)
      let vm =this
      vm.setData({
         search: e.detail.value
      })
     
   },
   Close(){
      let vm =this
      vm.setData({
         search:""
      })
      this.requestList();
   },

   onBindconfirm(){
      
      this.requestList();
   },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let vm =this    
    if (vm.data.total>0){

      this.setData({
        isRefreshing: true
      })

      if (vm.data.productList.length < vm.data.total) {
        vm.setData({
          page: vm.data.page + 1,
          isLoadingMoreData: true
        })
        vm.requestList(true)
      } else {
        this.setData({       
          isLoadingMoreData: false
        })
      }  

    }




  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
   getUserInfo() {
      AJAX('member/member-info', 'GET').then(res => {

         this.setData({
            level: res.data.level,            
         })
      })
   },
   // 获取滚动条当前位置
   onPageScroll: function (e) {    

      if (e.scrollTop > 30) {
         this.setData({
            tabPosition: true
           
         });
      } else {
         this.setData({
            tabPosition: false
           
         });
      }

      if (e.scrollTop > 200) {
         this.setData({
          
            floorstatus: true
         });
      } else {
         this.setData({
           
            floorstatus: false
         });
      }
   },
   goTop: function (e) {  // 一键回到顶部
      if (wx.pageScrollTo) {
         wx.pageScrollTo({
            scrollTop: 0
         })
      } else {
         wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
         })
      }
   },
  requestType() {
    let vm = this
    AJAX("product/category").then(res => {
      let _data = [{ category_id: "", category_name: "全部" }]
      if(res.data){
        for(let i in res.data){
          _data.push(res.data[i])
        }
      }
      vm.setData({
        typeList: _data
      })
    })
  },
  tabActive(e){
    let _id = e.currentTarget.dataset.type
    this.setData({
      activeNum:_id,
      page:1
    })
    this.requestList()
  },
  requestList(str){
    let vm =this
    AJAX("product/list","GET",{
       product_name:vm.data.search, //  input
      category_id: vm.data.activeNum ||'', // 分类
      page: vm.data.page, // 分页
       theme_id: vm.data.label_key, //标签
       days: vm.data.days_key, // 天数
       age_id: vm.data.age_key,   //年龄
       place_id: vm.data.address_key // 目的地
    }).then(res=>{  
       // 隐藏导航栏加载框
       wx.hideNavigationBarLoading();
       // 停止下拉动作
       wx.stopPullDownRefresh();      
      let _data = []
      if(str){
        _data = vm.data.productList
      }
     
       if (res.data!=''){
         res.data.forEach(function (item) {
         
            item.product_kind = productKind[item.product_kind || 1]
            item.theme_name = item.theme_name
            item.rake_back.two_level_profit = parseInt(item.rake_back.two_level_profit)
            item.rake_back.one_level_profit = parseInt(item.rake_back.one_level_profit)
            if (item.theme_name) {
               item.theme_name = item.theme_name.split('|')
            }
            item.pre_sales = parseInt(item.pre_sales) + parseInt(item.total_sales)
            _data.push(item)

         })
         vm.setData({
           productList: _data,
           total: res.header["X-Pagination-Total-Count"],
           hasNoData: false
         })
      }else{
         vm.setData({
           productList: res.data,
           total: res.header["X-Pagination-Total-Count"],
           isLoadingMoreData: false,
           hasNoData: true
         })
      }
     
    
     
    })
  },
  navBack(){
    wx.navigateBack()
  },
  toInfo(e){
    let _id =e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/product/productinfo/productinfo?id='+_id,
    })
  }
})